package com.bjsxt.lock3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 多个读操作可以同时进行，但读写、写写操作互斥
 */
public class TestReadWriteLock {

    public static void main(String[] args) {

        Operation operation = new Operation();

        Runnable readRunnable = new Runnable() {
            @Override
            public void run() {

                operation.read();
            }
        };
        //创建5个读线程并启动
        for (int i = 0; i < 5; i++) {

            new Thread(readRunnable, "读线程" + i).start();
        }

        Runnable writeRunnable = new Runnable() {
            @Override
            public void run() {

                operation.write();
            }
        };
        //创建5个写线程并启动
        for (int i = 0; i < 5; i++) {
            new Thread(writeRunnable, "写线程" + i).start();
        }
    }
}


class Operation {

    //private Lock lock = new ReentrantLock();
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void read() {

        // lock.lock();
        rwLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + "开始读数据...");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "读数据完毕...");
        } finally {
            //lock.unlock();
            rwLock.readLock().unlock();
        }
    }

    public void write() {


        //lock.lock();
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写数据...");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "写数据完毕...");
        } finally {
            //lock.unlock();
            rwLock.writeLock().unlock();
        }
    }
}